import request from '@/utils/request'
import { BASE_URL } from '@/utils/request'

export default {
  // 认证相关接口
  auth: {
    // 账号密码登录
    login: (data) => request.post('/api/v1/user/auth/login', data),

    // 退出登录
    logout: () => request.post('/api/v1/user/auth/logout'),

    // 用户注册
    register: (data) => request.post('/api/v1/user/auth/register', data),

    // 发送验证码
    sendVerifyCode: (phone, type = 1) => request.post('/api/v1/user/auth/verify-code', null, {
      params: { phone, type }
    })
  },

  // 用户角色相关接口
  role: {
    // 获取指定角色的用户列表
    getUsersByRole: (roleId) => request.get(`/api/v1/user/role/${roleId}/users`)
  },

  // 用户状态相关接口
  status: {
    // 更新用户状态
    update: (userId, status) => request.put(`/api/v1/user/status/${userId}`, null, {
      params: { status }
    })
  },

  // 个人资料相关接口
  profile: {
    // 获取个人资料
    get: () => request.get('/api/v1/user/profile'),

    // 更新个人资料
    update: (data) => request.put('/api/v1/user/profile', data),

    // 修改密码
    changePassword: (oldPassword, newPassword) => request.put('/api/v1/user/password', null, {
      params: { oldPassword, newPassword }
    }),

    // 上传头像
    uploadAvatar: (filePath) => {
      return new Promise((resolve, reject) => {
        // 获取 token
        const token = uni.getStorageSync('token')
        if (!token) {
          reject(new Error('请先登录'))
          return
        }

        uni.uploadFile({
          url: BASE_URL + '/api/v1/user/avatar',
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (uploadRes) => {
            try {
              const result = JSON.parse(uploadRes.data)
              if (result.code === 200) {
                resolve(result)
              } else {
                reject(new Error(result.message || '上传失败'))
              }
            } catch (e) {
              reject(new Error('解析响应数据失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },

    // 删除头像
    deleteAvatar: () => request.delete('/api/v1/user/avatar')
  },

  // 地址管理接口
  address: {
    // 获取地址列表
    list: () => request.get('/api/v1/user/address/list'),

    // 获取地址详情
    detail: (addressId) => request.get(`/api/v1/user/address/${addressId}`),

    // 获取默认地址
    getDefault: () => request.get('/api/v1/user/address/default'),

    // 添加地址
    add: (data) => request.post('/api/v1/user/address', data),

    // 更新地址
    update: (addressId, data) => request.put(`/api/v1/user/address/${addressId}`, data),

    // 删除地址
    delete: (addressId) => request.delete(`/api/v1/user/address/${addressId}`),

    // 设置默认地址
    setDefault: (addressId) => request.put(`/api/v1/user/address/${addressId}/default`)
  },

  // 收藏相关接口
  favorite: {
    // 获取收藏列表
    list: (params) => request.get('/api/v1/user/favorite/list', { params }),

    // 添加收藏
    add: (data) => request.post('/api/v1/user/favorite/add', data),

    // 取消收藏
    cancel: (id) => request.delete(`/api/v1/user/favorite/${id}`),

    // 检查是否已收藏
    check: (id) => request.get(`/api/v1/user/favorite/check/${id}`)
  },

  // 浏览历史接口
  history: {
    // 获取浏览历史列表
    list: (params = {}) => request.get('/api/v1/user/browse-history/list', {
      params: {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10,
        categoryId: params.categoryId
      }
    }),

    // 添加浏览历史
    add: (productId, data = {}) => request.post(`/api/v1/user/browse-history/${productId}`, null, {
      params: {
        categoryId: data.categoryId,
        stayDuration: data.stayDuration
      }
    }),

    // 删除单条浏览记录
    delete: (productId) => request.delete(`/api/v1/user/browse-history/${productId}`),

    // 清空浏览历史
    clear: () => request.delete('/api/v1/user/browse-history/clear')
  },

  // 地区相关接口
  region: {
    // 获取完整的地区树结构
    getRegionTree: () => request.get('/api/v1/user/region/tree'),

    // 获取省份列表
    getProvinces: () => request.get('/api/v1/user/region/provinces'),

    // 获取城市列表
    getCities: (provinceCode) => request.get(`/api/v1/user/region/cities/${provinceCode}`),

    // 获取区县列表
    getDistricts: (cityCode) => request.get(`/api/v1/user/region/districts/${cityCode}`),

    // 根据编码获取区域信息
    getByCode: (code) => request.get(`/api/v1/user/region/${code}`)
  },

  // 商品评论相关接口
  comment: {
    // 添加评论
    add: (data) => request.post('/api/v1/user/comments', {
      orderId: data.orderId,
      productId: data.productId,
      content: data.content,
      rating: data.rating,
      images: data.images,
      isAnonymous: data.isAnonymous || false
    }),

    // 删除评论
    delete: (commentId) => request.delete(`/api/v1/user/comments/${commentId}`),

    // 获取我的评论列表
    getMyComments: (params = {}) => request.get('/api/v1/user/comments/my', {
      params: {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10
      }
    }),

    // 点赞/取消点赞评论
    toggleLike: (commentId) => request.post(`/api/v1/user/comments/${commentId}/like`),

    // 获取评论详情
    getDetail: (commentId) => request.get(`/api/v1/user/comments/${commentId}/detail`),

    // 上传评论图片
    uploadImage: (file) => {
      const formData = new FormData()
      formData.append('file', file)
      return request.post('/api/v1/user/comments/upload/image', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    },
  },

  // 商家相关接口
  merchant: {
    // 申请成为商家
    apply: (data) => request.post('/api/v1/user/merchant/apply/merchant', data)
  },

  // 用户行为相关接口
  behavior: {
    // 记录用户浏览行为
    recordBrowse: (data) => request.post('/api/v1/user/behavior/browse', data),

    // 记录用户搜索行为
    recordSearch: (keyword) => request.post('/api/v1/user/behavior/search', null, {
      params: { keyword }
    }),

    // 获取用户分类偏好
    getCategoryPreferences: (limit = 5) => request.get('/api/v1/user/behavior/category-preferences', {
      params: { limit }
    }),

    // 清除搜索历史
    clearSearchHistory: () => request.delete('/api/v1/user/behavior/search-history')
  }


} 